package cn.tedu.charging.order.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttProducer {
    @Autowired
    private MqttClient mqttClient;
    //1.send 需要调用者提供qos topic message字符串 retained msgId
    public boolean doSend(String topic,String message,int qos,boolean retained,Integer msgId){
        //使用try cache 包裹
        try{
            //1.组织一个消息对象
            MqttMessage mqttMessage=new MqttMessage(message.getBytes());
            mqttMessage.setQos(qos);
            mqttMessage.setRetained(retained);
            if(msgId!=null){
                mqttMessage.setId(msgId);
            }
            //2.publish发送
            mqttClient.publish(topic,mqttMessage);
            return true;
        }catch (Exception e){
            log.error("发送消息异常",e);
            return false;
        }
    }
    //2.对doSend封装重载

    /**
     * @param topic: topic name
     * @param message: business data 对象可以转化成json
     * @return  boolean: true 发送成功 false 发送失败
     */
    public boolean send(String topic,String message){
        return this.doSend(topic,message,1,true,null);
    }
}
